package top.vanchor.flexible.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import top.vanchor.flexible.entity.BackAuthGroupRule;
import top.vanchor.flexible.mapper.BackAuthGroupRuleMapper;
import top.vanchor.flexible.service.IBackAuthGroupRuleService;
import org.springframework.stereotype.Service;
import top.vanchor.flexible.utils.JWTUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Ding
 * @since 2022-01-27
 */
@Log4j2
@Service
public class BackAuthGroupRuleServiceImpl extends ServiceImpl<BackAuthGroupRuleMapper, BackAuthGroupRule> implements IBackAuthGroupRuleService {

    @Resource
    private BackAuthGroupRuleMapper mapper;

    @Override
    public List<BackAuthGroupRule> getIdsByGroupId(Integer groupId) {
        QueryWrapper<BackAuthGroupRule> wrapper = new QueryWrapper<>();
        wrapper.eq("group_id",groupId);
        return mapper.selectList(wrapper);
    }

    @Override
    public List<Integer> getRuleIdsByGroupId(Integer groupId) {
        return mapper.getRuleIdsByGroupIdNotIncludeTopId(groupId);
    }

    @Override
    public int doRulesEdit(Integer groupId, List<Integer> ruleIds) {
        //先删除
        QueryWrapper<BackAuthGroupRule> wrapper = new QueryWrapper<>();
        wrapper.in("group_id",groupId);
        mapper.delete(wrapper);
        //再添加
        for (Integer ruleId : ruleIds) {
            BackAuthGroupRule bean = new BackAuthGroupRule();
            bean.setGroupId(groupId);
            bean.setRuleId(ruleId);
            mapper.insert(bean);
        }
        log.info("管理员{}（ID为{}）为角色（ID为{}）修改了权限规则，修改后的规则为：{}",JWTUtils.getAuthorName(),JWTUtils.getAuthorId(),groupId,ruleIds);
        return ruleIds.size();
    }

    @Override
    public String getIdsStringByGroupId(Integer groupId) {
        return mapper.getIdsStringByGroupId(groupId);
    }
}
